﻿using Compass.Wasm.Shared.Wms;
using Compass.Wpf.ApiServices;
using Compass.Wpf.ApiServices.Wms;
using Microsoft.Identity.Client.Extensions.Msal;
using SolidWorks.Interop.swconst;

namespace Compass.Wpf.ViewModels.Wms;

public class StockInsViewModel : NavigationViewModel
{

    #region ctor
    private readonly ICargoService _cargoService;
    private readonly IStockInService _stockInService;
    private readonly IPreferenceService _preferenceService;
    public StockInsViewModel(IContainerProvider provider) : base(provider)
    {
        _cargoService = provider.Resolve<ICargoService>();
        _stockInService= provider.Resolve<IStockInService>();
        _preferenceService = provider.Resolve<IPreferenceService>();

        StockInDto = new StockInDto();
        CargoDto=new CargoDto();

        CargoChangeCommand = new DelegateCommand(CargoChange);
        AddStockInCommand = new DelegateCommand(AddStockIn);
        UpdateStockInCommand = new DelegateCommand<StockInDto>(UpdateStockIn);
        DeleteStockInCommand = new DelegateCommand<StockInDto>(DeleteStockIn);
        SaveStockInCommand = new DelegateCommand(SaveStockIn);
        UpdateRoles = "admin,whse";
    }



    private string updateRoles;
    public string UpdateRoles
    {
        get => updateRoles;
        set { updateRoles = value; RaisePropertyChanged(); }
    }

    public DelegateCommand CargoChangeCommand { get; }
    public DelegateCommand AddStockInCommand { get; }
    public DelegateCommand<StockInDto> UpdateStockInCommand { get; }
    public DelegateCommand<StockInDto> DeleteStockInCommand { get; }
    public DelegateCommand SaveStockInCommand { get; }
    #endregion

    #region 右侧展开栏属性
    private bool isRightDrawerOpen;
    /// <summary>
    /// 右侧窗口是否展开
    /// </summary>
    public bool IsRightDrawerOpen
    {
        get => isRightDrawerOpen;
        set { isRightDrawerOpen = value; RaisePropertyChanged(); }
    }
    private string rightDrawerTitle = null!;
    public string RightDrawerTitle
    {
        get => rightDrawerTitle;
        set { rightDrawerTitle = value; RaisePropertyChanged(); }
    }

    private bool canSelectCargo;
    public bool CanSelectCargo
    {
        get => canSelectCargo;
        set { canSelectCargo = value; RaisePropertyChanged(); }
    }
    #endregion

    #region 属性
    private DateTime start;
    public DateTime Start
    {
        get => start;
        set
        {
            SetProperty(ref start, value);
            SearchAll = false;
        }
    }
    private DateTime end;
    public DateTime End
    {
        get => end;
        set
        {
            SetProperty(ref end, value);
            SearchAll = false;
        }
    }

    private string search;
    /// <summary>
    /// 搜索条件属性
    /// </summary>
    public string Search
    {
        get => search;
        set
        {
            SetProperty(ref search, value);
            Filter();
        }
    }
    private bool searchAll;
    /// <summary>
    /// 全范围搜索
    /// </summary>
    public bool SearchAll
    {
        get => searchAll;
        set
        {
            SetProperty(ref searchAll, value);
            GetDataAsync();
        }
    }
    private bool transit;
    public bool Transit
    {
        get => transit;
        set
        {
            SetProperty(ref transit, value);
            Filter();
        }
    }


    /// <summary>
    /// 用来选择物料
    /// </summary>
    private string keyword;
    public string Keyword
    {
        get => keyword;
        set
        {
            SetProperty(ref keyword, value);
            GetCargoDtos();
        }
    }
    private CargoDto cargoDto;
    public CargoDto CargoDto //当前选中的Cargo
    {
        get => cargoDto;
        set { cargoDto = value; RaisePropertyChanged(); }
    }

    private StockInDto stockInDto;
    public StockInDto StockInDto
    {
        get => stockInDto;
        set { stockInDto = value; RaisePropertyChanged(); }
    }
    public ObservableRangeCollection<StockInDto> StockInDtos { get; } = new();
    public ObservableRangeCollection<StockInDto> FilterStockInDtos { get; } = new();

    public ObservableRangeCollection<CargoDto> CargoDtos { get; } = new();
    #endregion
    
    #region 增删改查

    private async void FillStockInInfo()
    {
        if (CargoDto.Id != null || cargoDto.Id!=Guid.Empty)
        {
            StockInDto.CargoId = CargoDto.Id!.Value;
        }
        else
        {
            await DialogHost.Question("未查询到物料信息", "没有查询到物料信息！");
            return;
        }
        //StockInDto.MtlNumber = CargoDto.MtlNumber;
        //StockInDto.Description = CargoDto.Description;
        //StockInDto.Inventory=CargoDto.Inventory;
        //StockInDto.TransitIn=CargoDto.TransitIn;
        //StockInDto.TransitOut=CargoDto.TransitOut;
        //StockInDto.ShortAge = CargoDto.ShortAge;
        //StockInDto.Unit = CargoDto.Unit;
        //StockInDto.Location = CargoDto.Location;

        StockInDto.Operator=_preferenceService.Get(Consts.UserName);
        StockInDto.OperatorId=Guid.Parse(_preferenceService.Get(Consts.UserId)!);
        StockInDto.InTime=DateTime.Now;
    }

    private void CargoChange()
    {
        //选择Cargo时，将值赋值给当前的StockIn
        var cargo = CargoDtos.SingleOrDefault(x => x.IsSelected);
        if (cargo == null) return;
        CargoDto=cargo;

        FillStockInInfo();
        //todo:查询库存，用来计算入库差异
    }

    private async Task UpdatePrice()
    {
        //如果采购价格是0，则使用Cargo的LastPrice
        //如果采购价格不是0，则更新Cargo的LastPrice
        if (StockInDto.Price.Equals(0))
        {
            StockInDto.Price = CargoDto.LastPrice;
        }
        else
        {
            var oneYearStockIns = (await _stockInService.GetFromLastByCargoAsync(cargoDto.Id.Value,
                new DateTime(DateTime.Now.Year - 1, DateTime.Now.Month, DateTime.Now.Day))).Result;
            CargoDto.LastPrice = StockInDto.Price;
            CargoDto.AvgPrice = oneYearStockIns.Average(x => x.Price);
            await _cargoService.UpdateAsync(CargoDto.Id.Value, CargoDto);
        }
    }

    private void AddStockIn()
    {
        StockInDto = new StockInDto();
        IsRightDrawerOpen = true;
        CanSelectCargo = true;
        RightDrawerTitle = "添加入库记录";
    }

    private async void UpdateStockIn(StockInDto obj)
    {
        StockInDto=obj;
        var result = await _cargoService.GetFirstOrDefaultWithInventoryAsync(obj.CargoId);
        if (!result.Status) return;//没查到物料就返回
        CargoDto = result.Result;

        FillStockInInfo();

        IsRightDrawerOpen = true;
        CanSelectCargo = false;
        RightDrawerTitle = "修改入库记录";
    }

    private async void DeleteStockIn(StockInDto obj)
    {
        //删除询问
        var dialogResult = await DialogHost.Question("删除确认", $"确认删除物料入库记录：{obj.MtlNumber},{obj.Description}, 数量{obj.Quantity} 的入库记录吗?");
        if (dialogResult.Result != ButtonResult.OK) return;
        await _stockInService.DeleteAsync(obj.Id.Value);
        GetDataAsync();
    }


    private async void SaveStockIn()
    {
        //数据验证
        if (StockInDto.CargoId==Guid.Empty)
        {
            //发送提示
            Aggregator.SendMessage("物料不能为空，请选择物料");
            return;
        }
        if (StockInDto.Quantity==0)
        {
            //发送提示
            Aggregator.SendMessage("物料数量不能为0，请选择物料");
            return;
        }
        if (StockInDto.operatorId==Guid.Empty)
        {
            //发送提示
            Aggregator.SendMessage("没有登录？");
            return;
        }
        //在途为0则不判断，在途不为0则判断本次入库数量，不能大于在途
        if (StockInDto.TransitQuantity != 0 && StockInDto.TempQuantity>StockInDto.TransitQuantity)
        {
            //发送提示
            Aggregator.SendMessage($"本次入库数量{StockInDto.TempQuantity}不能大于在途数量{StockInDto.TransitQuantity}!");
            return;
        }

        if (StockInDto.TransitQuantity != 0)
        {
            StockInDto.TransitQuantity -= StockInDto.TempQuantity;//扣减在途
        }
        
        StockInDto.Quantity += StockInDto.TempQuantity;//增加入库



        try
        {
            if (StockInDto.Id != null && StockInDto.Id.Value != Guid.Empty)
            {
                await UpdatePrice();
                await _stockInService.UpdateAsync(StockInDto.Id.Value, StockInDto);
                Aggregator.SendMessage($"物料入库记录：{StockInDto.MtlNumber},{StockInDto.Description}, 数量:{StockInDto.Quantity} 修改成功！");
                StockInDto.Id=Guid.Empty;
            }
            else
            {
                await UpdatePrice();
                await _stockInService.AddAsync(StockInDto);
                Aggregator.SendMessage($"物料入库记录：{StockInDto.MtlNumber},{StockInDto.Description}, 数量:{StockInDto.Quantity} 添加成功！");
                StockInDto.Id=Guid.Empty;
            }
            IsRightDrawerOpen = false;
            GetDataAsync();
            GetCargoDtos();//查询物料也需要重新更新
        }
        catch (Exception e)
        {
            //发送错误报告
            Aggregator.SendMessage(e.Message);
        }
    }





    #endregion

    #region 筛选
    private void Filter()
    {
        FilterStockInDtos.ReplaceRange(
            StockInDtos.Where(x =>
                (!Transit||x.TransitQuantity>0)&&(
                string.IsNullOrEmpty(Search)||
                (!string.IsNullOrEmpty(x.MtlNumber)&&x.MtlNumber!.Contains(Search, StringComparison.OrdinalIgnoreCase))||
                (!string.IsNullOrEmpty(x.Description)&&x.Description!.Contains(Search, StringComparison.OrdinalIgnoreCase))||
                (!string.IsNullOrEmpty(x.Location)&&x.Location!.Contains(Search, StringComparison.OrdinalIgnoreCase))||
                (!string.IsNullOrEmpty(x.Remarks)&&x.Remarks!.Contains(Search, StringComparison.OrdinalIgnoreCase))
                )));

    }
    #endregion

    #region 导航和初始化
    //按照日期查询记录
    private void GetEnumNames()
    {
        //初始化一些枚举值

    }

    private async void GetDataAsync()
    {
        if (SearchAll) //不限制日期时搜索
        {
            var result = await _stockInService.GetAllAsync();
            if (result.Status)
            {
                StockInDtos.ReplaceRange(result.Result);
            }
        }
        else
        {
            var result = await _stockInService.GetAllByPeriodAsync(Start, End.AddDays(1));
            if (result.Status)
            {
                StockInDtos.ReplaceRange(result.Result);
            }
        }
        Filter();
    }
    public override void OnNavigatedTo(NavigationContext navigationContext)
    {
        base.OnNavigatedTo(navigationContext);
        Start=DateTime.Today;
        End=DateTime.Today;

        GetEnumNames();
        GetDataAsync();
        GetCargoDtos();
    }
    #endregion


    #region 增加入库记录时，搜索只返回5条物料记录
    private async void GetCargoDtos()
    {
        CargoDtos.ReplaceRange((await _cargoService.GetTop5ByKeywordWithInventoryAsync(Keyword)).Result);
    }
    #endregion
}